<template>
  <div class="product-category-container">
    <!-- 搜索栏 -->
    <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
      <el-input v-model="searchParams.name" style="width: 240px; padding-right: 15px;" placeholder="请输入类别名称" />
      <el-select v-model="searchParams.status" style="width: 150px; margin-right: 15px;" placeholder="请选择状态" clearable>
        <el-option label="启用" :value="1" />
        <el-option label="禁用" :value="0" />
      </el-select>
      <el-icon @click="getCategoryList()" style="margin-left: 20px; height: 25px; width: 25px;">
        <Search />
      </el-icon>
      <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
        <Refresh />
      </el-icon>
      <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建类别</el-button>
    </div>

    <!-- 商品类别表格 -->
    <el-table :data="categoryList" style="width: 100%" stripe border="true">
      <el-table-column label="序号" width="80px" #default="scope" align="center">
        {{ scope.$index + 1 }}
      </el-table-column>
      <el-table-column prop="name" label="类别名称" width="200" align="center" />
      <el-table-column label="父类别" width="200" align="center">
        <template #default="scope">
          {{ getParentCategoryName(scope.row.parentId) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" #default="scope" align="center">
        <span v-if="scope.row.status == 1" style="color: green;">启用</span>
        <span v-if="scope.row.status == 0" style="color: red;">禁用</span>
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center" />
      <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
        <el-button type="primary" plain @click="showEditDialog(scope.row)">修改</el-button>
        <el-button type="danger" plain @click="deleteCategory(scope.row.id)">删除</el-button>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination 
        v-model:current-page="pagination.pageNum" 
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="pagination.total"
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange" 
      />
    </div>

    <!-- 创建/编辑类别对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑商品类别' : '创建商品类别'" width="600px"
      :before-close="handleDialogClose" :close-on-click-modal="false">
      <el-form :model="categoryForm" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="categoryFormRef">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入类别名称" />
        </el-form-item>
        <el-form-item label="父类别" prop="parentId">
          <el-select v-model="categoryForm.parentId" placeholder="请选择父类别" clearable>
            <el-option label="无父类别" :value="null" />
            <el-option v-for="category in allCategories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" :step="1" :precision="0" controls-position="default" style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="categoryForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="categoryForm.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { productCategoryApi } from '@/api/product/product'

// 响应式数据
const categoryList = ref([])
const allCategories = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const categoryFormRef = ref()

// 搜索参数
const searchParams = reactive({
  name: '',
  status: null
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 类别表单
const categoryForm = reactive({
  id: null,
  name: '',
  parentId: null,
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入类别名称', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取类别列表
const getCategoryList = async () => {
  try {
    const params = {
      current: pagination.pageNum,
      size: pagination.pageSize,
      ...searchParams
    }
    
    const response = await productCategoryApi.list(params)
    
    if (response && response.records) {
      categoryList.value = response.records
      pagination.total = response.total
    } else {
      ElMessage.error('获取类别列表失败')
    }
  } catch (error) {
    console.error('获取类别列表失败:', error)
    ElMessage.error('获取类别列表失败')
  }
}

// 获取所有类别（用于下拉选择）
const getAllCategories = async () => {
  try {
    const response = await productCategoryApi.all()
    if (response && Array.isArray(response)) {
      allCategories.value = response
    }
  } catch (error) {
    console.error('获取所有类别失败:', error)
  }
}

// 获取父类别名称
const getParentCategoryName = (parentId) => {
  if (!parentId) return '无'
  const parent = allCategories.value.find(c => c.id === parentId)
  return parent ? parent.name : '未知'
}

// 重置搜索参数
const resetSearchParams = () => {
  Object.assign(searchParams, {
    name: '',
    status: null
  })
  pagination.pageNum = 1
  getCategoryList()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  Object.assign(categoryForm, {
    id: null,
    name: '',
    parentId: null,
    sort: 0,
    status: 1,
    remark: ''
  })
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(categoryForm, {
    id: row.id,
    name: row.name,
    parentId: row.parentId,
    sort: row.sort,
    status: row.status,
    remark: row.remark
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await categoryFormRef.value.validate()
    
    const api = isEdit.value ? productCategoryApi.update : productCategoryApi.add
    const response = await api(categoryForm)
    
    if (response && response.success) {
      ElMessage.success(isEdit.value ? '类别更新成功' : '类别创建成功')
      dialogVisible.value = false
      getCategoryList()
      getAllCategories()
    } else {
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除类别
const deleteCategory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该类别吗？', '提示', {
      type: 'warning'
    })
    
    const response = await productCategoryApi.delete(id)
    
    if (response && response.success) {
      ElMessage.success('删除成功')
      getCategoryList()
      getAllCategories()
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除类别失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  categoryFormRef.value?.resetFields()
  dialogVisible.value = false
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  getCategoryList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.pageNum = current
  getCategoryList()
}

// 初始化
onMounted(() => {
  getCategoryList()
  getAllCategories()
})
</script>

<style scoped>
.product-category-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar .el-icon {
  cursor: pointer;
  color: #409eff;
}

.search-bar .el-icon:hover {
  color: #66b1ff;
}
</style>
